<script setup>
import {nextTick, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {addTypeSet, findTypeSetById} from "@/apis/zyj/typeSetting.js";

const props = defineProps({
  allUnits: Array,
  addDialog: Boolean,
})
// 表单数据
const form = reactive({
  typeCode: '',
  typeName: '',
  isCodeManaged: '0',
  maintenanceType: '',
  maintenancePeriod: '',
  remark: ''
})
const ruleForm = reactive({...form})
const ruleFormRef = ref();//表单验证
const isSwitch = ref(false)


function createID() {
  let code = 'TT';
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  code = code + year + month + strDate + Math.floor(Math.random() * 10000);
  console.log(code)
  return code;
}

// 自动生成员工编码
const switchCode = (value) => {
  let code = createID();
  if (value) {
    form.typeCode = code
  } else {
    form.typeCode = ''
  }
}

// 自定义事件
const emit = defineEmits(['close-dialog'])
// 关闭弹窗
const handleClose = () => {
  Object.assign(form, ruleForm)
  isSwitch.value = false
  emit('close-dialog')
}

// 确定按钮
const handleConfirm = (value) => {
  console.log(12, form)
  value.validate(valid => {
    if (valid) {
      addTypeSet(form).then(req => {
        console.log(req)
        if (req === '成功') {
          ElMessage.success('添加成功')
        } else {
          ElMessage.error('添加失败')
        }
        handleClose()
      })
    } else ElMessage.error('请填写完整信息');
  });
}

// 打开弹窗时清空校验
const handleOpenCardDialog = () => {
  nextTick(() => {
    // 清空校验
    ruleFormRef.value.clearValidate()
  })
}

// 校验编码是否重复
const validateCode = (rule, value, callback) => {
  findTypeSetById(value).then(res => {
    console.log(res)
    if (res) {
      callback(new Error('该编码已存在'))
    } else {
      callback()
    }
  })
}
const isNumber=(rule, value, callback)=>{
  if (isNaN(value)) {
    callback(new Error('请输入数字'))
  } else {
    callback()
  }
}

const rules = {
  typeCode: [
    {required: true, message: '请输入类型编码', trigger: 'blur'},
    {validator: validateCode, trigger: 'blur'}
  ],
  typeName: [
    {required: true, message: '请输入类型名称', trigger: 'blur'},
  ],
  isCodeManaged: [
    {required: true, message: '请选择是否编码管理', trigger: 'blur'},
  ],
  maintenancePeriod: [
    //必须是数字
    {validator: isNumber, trigger: 'blur'}
  ]
}
</script>

<template>
  <div class="dialog-class">
    <el-dialog title="添加工装夹具类型" v-model="props.addDialog" @close="handleClose" @open="handleOpenCardDialog"
               width="55%">
      <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型编码" prop="typeCode">
              <el-input v-model="form.typeCode" placeholder="请输入类型编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="margin-top:10px">
            <el-switch
                v-model="isSwitch"
                active-text="自动生成"
                @change="switchCode"
                style="width: 80px"/>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-form-item label="类型名称" prop="typeName">
              <el-input v-model="form.typeName" placeholder="请输入类型名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="flex-wrap: nowrap;">
          <el-col :span="8">
            <el-form-item label="是否编码管理" prop="isCodeManaged">
              <el-radio-group v-model="form.isCodeManaged">
                <el-radio label="0" value="0">是</el-radio>
                <el-radio label="1" value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <div style="display: flex" v-show="form.isCodeManaged === '0'">
            <el-form-item label="保养维护类型">
              <el-select v-model="form.maintenanceType" placeholder="请选择保养维护类型" style="width: 180px">
                <el-option label="定期维护" value="定期维护"/>
                <el-option label="按使用次数维护" value="按使用次数维护"/>
              </el-select>
            </el-form-item>
            <el-form-item label="保养周期" prop="maintenancePeriod">
              <el-input v-model="form.maintenancePeriod" placeholder="请输入保养周期"/>
            </el-form-item>
          </div>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注">
              <el-mention
                  v-model="form.remark"
                  type="textarea"
                  style="width: 320px"
                  placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
         <span class="dialog-footer">
           <el-button @click="handleClose">取消</el-button>
           <el-button type="primary" @click="handleConfirm(ruleFormRef)">确定</el-button>
         </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
:deep(.el-dialog__body) {
  padding: 20px 20px 20px 0;
}

::v-deep(.el-form-item__label) {
  color: #606266;
  font-size: 14px;
  font-weight: 700;
  margin: 10px 0;
}

</style>